package org.wtframework.platform.web.mvc.action.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.openredhead.springx.core.server.page.IPage;
import org.openredhead.springx.core.web.mvc.support.ActionValueAssistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wtframework.platform.server.log.SystemControllerLog;
import org.wtframework.platform.server.manager.impl.FileMetaManager;
import org.wtframework.platform.server.manager.impl.GroupManager;
import org.wtframework.platform.server.manager.impl.LogRecordManager;
import org.wtframework.platform.server.manager.impl.ResourceManager;
import org.wtframework.platform.server.manager.impl.RoleManager;
import org.wtframework.platform.server.manager.impl.UserIdentityManager;
import org.wtframework.platform.server.manager.impl.UserManager;
import org.wtframework.platform.server.model.impl.FileMeta;
import org.wtframework.platform.server.model.impl.Group;
import org.wtframework.platform.server.model.impl.Resource;
import org.wtframework.platform.server.model.impl.Role;
import org.wtframework.platform.server.model.impl.User;
import org.wtframework.platform.server.model.impl.UserIdentity;
import org.wtframework.platform.server.service.BackManagerService;
import org.wtframework.platform.server.util.ExportExcelUtil;
import org.wtframework.platform.server.util.FilePath;
import org.wtframework.platform.server.util.ImportExcelUtil;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


@Controller
@RequestMapping("/back/base")
public class BackBaseActionController {
	
	private static String BASE_URL = "admin/back_layui/base";
	
	@Autowired
	private BackManagerService backManagerService;
		
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private UserIdentityManager userIdentityManager;
	
	@Autowired
	private RoleManager roleManager;
	@Autowired
	private GroupManager groupManager;
	
	@Autowired
	private FileMetaManager fileMetaManager;
	
	@Autowired
	private LogRecordManager logRecordManager;
	
	@Autowired
	private ResourceManager resourceManager;
	
	private static Map<String, Object> tempValueMap = Maps.newHashMap();
		
	/**
	 * 
	 * <B>方法描述：</B>（用户列表） <br/>
	 *
	 * <B>作者：	 </B> 黄杰帆 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入用户列表页")
	@RequestMapping("/userList")
	public String userList(ModelMap modelMap,ActionValueAssistant actionValueAssistant){
		
		int currentpage = 1;

		String page = actionValueAssistant.getString("page");
		if (page != null) {
			currentpage = Integer.parseInt(page.trim());
		}

		Integer groupId = actionValueAssistant.get(Integer.class, "groupId");
		Integer indentifyId = actionValueAssistant.get(Integer.class, "indentifyId");
		String username = actionValueAssistant.getString("username");
		
		modelMap.put("userPage", backManagerService.userListSearch(groupId, indentifyId, username, currentpage, 10));
		List<Group> resultList = Lists.newArrayList();
		resultList.addAll(backManagerService.getGroupList(1));
		resultList.addAll(backManagerService.getGroupList(2));
		Map<Integer, String> resultMap = Maps.newHashMap();
		for(Group group : resultList) {
			resultMap.put(group.getId(), group.getName());
		}
		
		modelMap.put("resultMap",resultMap);
		modelMap.put("identifyPage",userIdentityManager.loadAll().getPage());
		
		actionValueAssistant.addToModelMap(modelMap);
		
		return BASE_URL + "/user/userManager";
	}
	
	@RequestMapping("/userData")
	@ResponseBody
	public Map<String,Object> userData(ModelMap modelMap,ActionValueAssistant actionValueAssistant){
		
		try {
			Map<String,Object> resultMap = Maps.newHashMap();
			Integer pageNo = actionValueAssistant.get(Integer.class, "page");
			Integer pageSize = actionValueAssistant.get(Integer.class, "limit");
			Integer groupId = actionValueAssistant.get(Integer.class, "groupId");
			Integer indentifyId = actionValueAssistant.get(Integer.class, "indentifyId");
			String username = actionValueAssistant.getString("username");
			if(pageNo==null) {
				pageNo = 1;
			}
			IPage<User> userPage = backManagerService.userListSearch(groupId, indentifyId, username, pageNo, pageSize);
			List<Map<String,Object>> list = Lists.newArrayList();
			//"id","username","nickname","iendtifyName","identityId","roleIdList"
			Map<Integer,List<Integer>> ident_roleMap= backManagerService.getUserIdentityToRoleIdMap();
			Map<Integer,List<Integer>> par_roleMap = backManagerService.getGroupToRoleIdMap();
			Map<Integer,String> groupMap = backManagerService.groupMap();
			Map<Integer,String> roleMap = backManagerService.roleMap();
			Map<Integer,String> identifyMap = backManagerService.identifyMap();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(User u : userPage.getData()){
				Map<String,Object> map = Maps.newHashMap();
				map.put("id", u.getId());
				map.put("username", u.getUsername());
				map.put("nickname", u.getNickname());
				map.put("identityId",u.getIdentityId());
				map.put("iendtifyName", identifyMap.get(u.getIdentityId()));
				map.put("groupId", u.getParentId());
				map.put("groupName", groupMap.get(u.getParentId()));
				map.put("establishDate", sdf.format(u.getEstablishDate()));
				List<Integer> roleIdList = Lists.newArrayList();
				for(Integer i : u.getRolesId()){
					if(!roleIdList.contains(i)){
						roleIdList.add(i);
					}
				}
				try {
					for(Integer i : ident_roleMap.get(u.getIdentityId())){
						if(!roleIdList.contains(i)){
							roleIdList.add(i);
						}
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(u.getParentId()!=null){
					for(Integer i : par_roleMap.get(u.getParentId())){
						if(!roleIdList.contains(i)){
							roleIdList.add(i);
						}
					}
				}
				String nameStrs = "";
				for(Integer i : roleIdList){
					nameStrs+=roleMap.get(i)+",";
				}
				if(nameStrs.length()>0){
					nameStrs = nameStrs.substring(0, nameStrs.length()-1);
				}
				map.put("roleNameList", nameStrs);
				map.put("roleidList", roleIdList);
				list.add(map);
				
			}
			resultMap.put("code", 0);
			resultMap.put("count", userPage.getTotalCount());
			resultMap.put("data", list);
			return resultMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		
	}
	
	
	/**
	 * 
	 * <B>方法描述：</B>（用户信息编辑页面） <br/>
	 *
	 * <B>作者：	 </B> 黄杰帆 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入用户信息编辑页面")
	@RequestMapping("/userEdit")
	public String userEditUI(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		
		String userId = actionValueAssistant.get(String.class,"userId");
		userId = userId.trim();
		if(!Strings.isNullOrEmpty(userId)) {
			modelMap.put("user", userManager.load(Long.parseLong(userId.trim())));
		}
		modelMap.put("userIdentitys", backManagerService.getUserIdentityList());
		
		return BASE_URL + "/user/userEdit";
	}
	
	@RequestMapping("/userRoleEditUI")
	public String userRoleEditUI(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		
		String userId = actionValueAssistant.get(String.class,"id");
		List<Role> roleList = backManagerService.loadRoleList();
	  	User user = userManager.load(Long.parseLong(userId.trim()));
		Integer userIdentityId = user.getIdentityId();
		UserIdentity userIdentity = userIdentityManager.load(userIdentityId);	
		List<Integer> roleIdList1 = userIdentity.getRolesId();
		List<Integer> roleIdList2 = user.getRolesId();
		Map<Integer, Boolean> roleMap = Maps.newHashMap();
		Map<Integer, Boolean> roleMap2 = Maps.newHashMap();
		for(Integer i : roleIdList1){
			roleMap.put(i, true);
		}
		for(Integer i:roleIdList2){
			roleMap2.put(i,true);
		}
		modelMap.put("roleIdList", roleIdList1);
		modelMap.put("roleMap", roleMap);
		modelMap.put("roleMap2", roleMap2);
		modelMap.put("roleList", roleList);
		modelMap.put("user", user);	
		return "base_layui/from_templet/user_role_edit_form";
	}
	
	

	/**
	 * 
	 * <B>方法描述：</B>（职能部门管理页面） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入职能部门管理页面")
	@RequestMapping("/group")
	public String groupDefault(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {

		return BASE_URL + "/group/gradeManager";
	}
	@RequestMapping("/groupEdit/{groupId}")
	public String groupEdit(@PathVariable Integer groupId, ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		try {
			Integer flag = actionValueAssistant.get(Integer.class, "flag");
			if(groupId==0){
				groupId =  null;
			}
			if(flag == 0 ) {
				modelMap.put("group", groupManager.load(groupId));
			}else{
			    modelMap.put("groupId", groupId);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		
		return "base_layui/from_templet/group_edit_from";
	}
	
	@RequestMapping("/gradeEdit/{gradeId}")
	public String gradeEdit(@PathVariable Integer gradeId, ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		try {
			Integer flag = actionValueAssistant.get(Integer.class, "flag");
			if(gradeId==0){
				gradeId =  null;
			}			if(flag == 0 ) {
				modelMap.put("group", groupManager.load(gradeId));
			}else{
			    modelMap.put("groupId", gradeId);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		
		return "base_layui/from_templet/grade_edit_from";
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（职能部门管理页面） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入职能部门管理页面")
	@RequestMapping("/group/{sortId}")
	public String group(@PathVariable Integer sortId, ModelMap modelMap, ActionValueAssistant actionValueAssistant) {
		
		if(sortId == null) {
			sortId = 1;
		}
		if(sortId == 1) {
			return BASE_URL + "/group/gradeManager";
		} else if(sortId == 2) {
			return BASE_URL + "/group/gradeManager";
		} else {
			return BASE_URL + "/group/gradeManager";
		}
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（所有职能部门JSON数据） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@RequestMapping("/group-json")
	public @ResponseBody List<Map<String, Object>> groupList(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {
		
		Integer sortId = actionValueAssistant.get(Integer.class, "sortId");
		List<Map<String, Object>> resourceList = Lists.newArrayList();
		List<Group> resultList = Lists.newArrayList();
		if(sortId == -1) {
			resultList.addAll(backManagerService.getGroupList(1));
			resultList.addAll(backManagerService.getGroupList(2));
		} else {
			resultList.addAll(backManagerService.getGroupList(sortId));
		}
		
		for(Group group : resultList) {
			
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", group.getId());
			map.put("name", group.getName());
			map.put("parentId", group.getParentId());
			map.put("descn", group.getDescn());
			map.put("orderId", group.getOrderId());			
			map.put("rolesId", group.getRolesId());			
			map.put("sortId", group.getSortId());			
			map.put("icon", "/style/jw/images/fam/group.png");
			if(group.getParentId() == null) {
				map.put("open", true);
			}
			
			resourceList.add(map);
		}
		
		return resourceList;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（权限资源管理页面） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入权限资源管理页面")
	@RequestMapping("/resource")
	public String resource(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {
		
		return BASE_URL + "/resource/resourceManager";
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（所有权限资源JSON数据） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@RequestMapping("/resource-json")
	public @ResponseBody List<Map<String, Object>> resourceList(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {
		try {
			List<Map<String, Object>> resourceList = Lists.newArrayList();
			for(Resource resource : backManagerService.getResourceList()) {
				
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", resource.getId());
				map.put("name", resource.getName());
				map.put("identifier", resource.getIdentifier());
				map.put("parentId", resource.getParentId());
				map.put("url", resource.getUrl());
				map.put("method", resource.getMethod());
				map.put("menuUrl", resource.getMenuUrl());
				map.put("sensitivity", resource.getSensitivity());
				map.put("descn", resource.getDescn());
				map.put("orderId", resource.getOrderId());
				
				if(resource.getParentId() == null) {
					
					map.put("icon", "/style/jw/images/fam/folder_key.png");
					map.put("open", true);
				} else if(resource.getChildsId().size() == 0) {
					map.put("icon", "/style/jw/images/fam/key.png");
				} else {
					map.put("icon", "/style/jw/images/fam/folder_key.png");
				}
				resourceList.add(map);
			}
			return resourceList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("/resourceEdit/{resourceId}")
	public String resourceEdit(@PathVariable Integer resourceId, ModelMap modelMap, ActionValueAssistant actionValueAssistant){
			Integer flag = actionValueAssistant.get(Integer.class, "flag");
			if(resourceId==0){
				resourceId = null;
			}
			if(flag == 0 ) {
				modelMap.put("resource", resourceManager.load(resourceId));
			}else{
			    modelMap.put("resourceId", resourceId);
			}
		return "base_layui/from_templet/resource_edit_from";
	}
	
	
	
	/**
	 * 
	 * <B>方法描述：</B>（用户身份列表） <br/>
	 *
	 * <B>作者：	 </B> 黄杰帆 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入用户身份列表页")
	@RequestMapping("/userIdentityList")
	public String userIdentityList(ModelMap modelMap,ActionValueAssistant actionValueAssistant){	
		return BASE_URL + "/userIdentity/userIdentityManager";
	}
	
	/*
	 * 用户身份管理表格数据Api
	 */
	@RequestMapping("/userIdentityData")
	@ResponseBody

	public Map<String,Object> userIdentityData(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		try {
			Map<String,Object> resultMap = Maps.newHashMap();
			Integer pageNo = actionValueAssistant.get(Integer.class, "page");
			Integer pageSize = actionValueAssistant.get(Integer.class, "limit");
			String name = actionValueAssistant.getString("name");	
			if(pageNo==null) {
				pageNo = 1;
			}
			IPage<UserIdentity> userIdentityPage = backManagerService.userIdentityListSearch(name, pageNo, pageSize);		
			List<Map<String,Object>> list = Lists.newArrayList();			
			Map<Integer,List<Integer>> ident_roleMap= backManagerService.getUserIdentityToRoleIdMap();		
			
			for(UserIdentity uidtity : userIdentityPage.getData()){
				Map<String,Object> map = Maps.newHashMap();
				map.put("id", uidtity.getId());
				map.put("name", uidtity.getName());
				map.put("initScore", uidtity.getInitScore());
				map.put("IsDefault", uidtity.getIsDefault());
				map.put("descn", uidtity.getDescn());
			//	map.put("rolesId", uidtity.getRolesId());
		    //	map.put("rolesId", ident_roleMap.get(uidtity.getRolesId()));
				map.put("roleNameList", "");
				List<Integer> roleIdList = Lists.newArrayList();
				for(Integer i : uidtity.getRolesId()){
					if(!roleIdList.contains(i)){
						roleIdList.add(i);
					}
				}
				map.put("roleIdList", roleIdList);				
				list.add(map);				
			}
			resultMap.put("data", list);
			resultMap.put("code", 0);
			resultMap.put("count", userIdentityPage.getTotalCount());	
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;

		}
		
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（用户身份编辑UI） <br/>
	 *
	 * <B>作者：	 </B> 徐嘉航 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	
	@RequestMapping("/userIdentityEditUI")
	public String userIdentityEditUI(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		
		Integer userIdentityId = actionValueAssistant.get(Integer.class,"id");		
        //Integer roleIdList = actionValueAssistant.get(Integer.class,"roleIdList");
		
		List<Role> roleList = backManagerService.loadRoleList();
		UserIdentity userIdentity = userIdentityManager.load(userIdentityId);
		if(userIdentityId!=null){
			List<Integer> roleIdList = userIdentity.getRolesId();
			Map<Integer, Boolean> roleMap = Maps.newHashMap();
			for(Integer i : roleIdList){
				roleMap.put(i, true);
		    }
			modelMap.put("roleIdList", roleIdList);
			modelMap.put("roleMap", roleMap);
		}
		modelMap.put("roleList", roleList);		
		modelMap.put("userIdentity", userIdentity);
		return "base_layui/from_templet/userIdentity_edit_form";
	}
	
	
	/**
	 * 
	 * <B>方法描述：</B>（角色列表） <br/>
	 *
	 * <B>作者：	 </B> 黄杰帆 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入用户角色页面")
	@RequestMapping("/roleList")
	public String roleList(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {
		
		return BASE_URL + "/role/roleManager";
	}
	
	@RequestMapping("/roleData")
	@ResponseBody
	public Map<String,Object> roleData(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		Map<String,Object> resultmap = Maps.newHashMap();
		Integer pageNo = actionValueAssistant.get(Integer.class, "page");
		Integer pageSize = actionValueAssistant.get(Integer.class, "limit");
		String name = actionValueAssistant.getString("name");
		if(pageNo==null) {
			pageNo = 1;
		}
//		IPage<Role> roleIPage=backManagerService.roleListSearch(name, pageNo, pageSize);
//		List<Map<String, Object>> list = Lists.newArrayList();
//		for (Role r:roleIPage.getData()) {
//			Map<String, Object> map = Maps.newHashMap();
//			map.put("id", r.getId());
//			map.put("name", r.getName());
//			list.add(map);		
//		}
		List<Object> valueList = Lists.newArrayList();
		String hql = "select id,name from Role";
		if(!Strings.isNullOrEmpty(name)){
			hql+="where name like ? ";
			valueList.add("%"+name+"%");		
		}
		IPage<Map<String,Object>> page = roleManager.findProperty(new String[]{"id","name"}, hql, valueList.toArray()).getPageByPageNo(pageNo, pageSize);
	
		resultmap.put("code", 0);
		resultmap.put("count",page.getTotalCount());
		resultmap.put("data", page.getData());
		
		return resultmap;
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（用户身份编辑UI） <br/>
	 * 
	 * <B>作者： </B> 黄杰帆 <br/>
	 * 
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@RequestMapping("/roleEditUI")
	public String roleEditUI(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {

		Integer roleId = actionValueAssistant.get(Integer.class, "roleId");

		if (roleId != null) {
			modelMap.put("role", roleManager.load(roleId));
		}
		return "base_layui/from_templet/role_edit_form";
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（待审核列表） <br/>
	 *
	 * <B>作者：	 </B> 黄杰帆 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="进入用户审核页面")
	@RequestMapping("/userAuditList")
	public String userAudit(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		
		int currentpage = 1;
		
		String page = actionValueAssistant.getString("page");
		if(page!=null) {
			currentpage = Integer.parseInt(page.trim());
		}
		
		String username = actionValueAssistant.getString("username");
		
		if(Strings.isNullOrEmpty(username)){
			
			modelMap.put("userPage", userManager.find(new String[]{"approval","locked"}, new Object[]{0,false}).getPageByPageNo(currentpage, 10));
		} else {
			modelMap.put("userPage", backManagerService.userAuditSearch(username, currentpage, 10));
		}
		
		modelMap.put("page", page);
		modelMap.put("username", username);
		return BASE_URL + "/userAudit/userAuditManager";
	}
	/*
	 * 用户审批表格数据Api
	 */
	@RequestMapping("/userAuditData")
	@ResponseBody
	public Map<String,Object> userAuditData(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		Map<String,Object> map = Maps.newHashMap();
		Integer pageNo = actionValueAssistant.get(Integer.class, "page");
		Integer pageSize = actionValueAssistant.get(Integer.class, "limit");
		String username = actionValueAssistant.getString("username");
		if(pageNo==null) {
			pageNo = 1;
		}
		List<Object> valueList = Lists.newArrayList();
		String hql = "select id,username,nickname,date_format(establishDate, '%Y-%m-%d %H:%i') from User where approval = 0 and locked = ? ";
		valueList.add(false);
		if(!Strings.isNullOrEmpty(username)){
			hql+="and (username like ? or nickname like ?) ";
			valueList.add("%"+username+"%");
			valueList.add("%"+username+"%");
		}
		IPage<Map<String,Object>> page = userManager.findProperty(new String[]{"id","username","nickname","createTime"}, hql, valueList.toArray()).getPageByPageNo(pageNo, pageSize);
		map.put("code", 0);
		map.put("count", page.getTotalCount());
		map.put("data", page.getData());
		return map;
		
		
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（用户详细信息） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@RequestMapping("/userdetail")
	public String userdetail(ModelMap modelMap, ActionValueAssistant actionValueAssistant){
		
		String userId = actionValueAssistant.get(String.class,"userId");
		
		if(userId != null ) {
			modelMap.put("user", userManager.load(Long.parseLong(userId.trim())));
		}
		return "base_layui/from_templet/user_audit_form";
	}
	
	
	@RequestMapping("/userimportUI")
	public String userImportUI(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {

		return "base_layui/from_templet/user_import_form";
	}

	/**
	 * 
	 * <B>方法描述：</B>（批量导入用户） <br/>
	 *
	 * <B>作者：	 </B> 梁卓文 <br/>
	 * @param modelMap
	 * @param actionValueAssistant
	 * @return
	 */
	@SystemControllerLog(description="批量导入用户")
	@SuppressWarnings("unchecked")
	@RequestMapping("/importxls")
	public @ResponseBody
	Map<String ,Object> userImportxls(ModelMap modelMap, ActionValueAssistant actionValueAssistant) {

		Long id = actionValueAssistant.get(Long.class, "id");
		
		System.out.println(id);
		FileMeta fileMeta = fileMetaManager.load(id);
		
		System.out.println(fileMeta);
		
		String filePath = fileMeta.getFileUrl().replace("\\", "/");
		
		File excelFile = new File(FilePath.getSystemRootPath() + filePath);
		
		if(!excelFile.exists()){
			System.out.println("文件不存在！");
		}
		String message = "数据校验完成，无错误 ;";
		Object o = ImportExcelUtil.importUserExcel(excelFile, userManager, userIdentityManager, groupManager);
		List<Object> resultList  = Lists.newArrayList();
		
		if(o instanceof String){
			message = o.toString();
		}else {
			
			List<Object> tempList = (List<Object>) o;
			message = "";
			List<String> errorInfo = (List<String>) tempList.get(tempList.size()-1);
			for(String err : errorInfo){
				message += err +" ;";
			}
			message = message + "共"+(tempList.size()-1)+"行数据需要导入 ;";
			if(tempList.size() > 1) {
				System.out.println("tempList : "+tempList);
				for(int i=0 ; i< tempList.size()-1; i++){
					resultList.add(tempList.get(i));
				}
			}
		}

		Map<String ,Object> result = Maps.newHashMap();
		
		String tempKey = UUID.randomUUID() + "";
		tempValueMap.put(tempKey, resultList);
		
		result.put("message", message);
		result.put("key", tempKey);
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/importxls/{key}")
	public @ResponseBody
	Integer userImportxlsAdd(@PathVariable String key, ModelMap modelMap, ActionValueAssistant actionValueAssistant) {

		if(tempValueMap.get(key) == null) {
			return null;
		}
		
		List<Object> userList = (List<Object>) tempValueMap.get(key);
		Integer count = 0;
		for(Object temp : userList) {
			Map<String, Object> userInfo = (Map<String, Object>)temp;
			User user = new User();
			user.setUsername(userInfo.get("username") + "");
			user.setNickname(userInfo.get("nickname") + "");
			user.setPhoneNumber(userInfo.get("phone") + "");
			user.setEmail(userInfo.get("email") + "");
			user.setPassword(DigestUtils.md5Hex("111111"));
			user.setApproval(1);
			if(userInfo.get("identify") != null){
				user.setIdentityId(Integer.valueOf(userInfo.get("identify")+""));
				//user.setUnableScore(Double.valueOf(userInfo.get("score") + ""));
			} else {
				UserIdentity userIdentity = userIdentityManager.getDefalutUserIdentity();
				if (userIdentity != null) {
					user.setIdentityId(userIdentity.getId());
					user.setUnableScore(userIdentity.getInitScore());
				}
			}
			//随机生成头像
			String[] imageArray = new String[]{"tou_a.jpg", "tou_b.jpg", "tou_c.jpg", "tou_d.jpg", "tou_e.jpg", "tou_f.jpg", "tou_g.jpg", "tou_h.jpg"};
			Random rand = new Random();
			Integer tem = rand.nextInt(8);
			String imagestr = "/style/back/image/" + imageArray[tem];
			user.setImageUrl(imagestr);
			
			if(userInfo.get("groupId")  != null){
				user.setParentId(Integer.valueOf(userInfo.get("groupId")+""));
			}
			userManager.save(user);
			count ++;
		}
		
		return count;
	}

	@SystemControllerLog(description="导出用户")
	@RequestMapping("/exportUser")
	public @ResponseBody String exportUser(ModelMap modelMap, ActionValueAssistant actionValueAssistant ) {
		
		try {
			List<User> userList = backManagerService.loadAllUser();
			
			List<Group> resultList = Lists.newArrayList();
			resultList.addAll(backManagerService.getGroupList(1));
			resultList.addAll(backManagerService.getGroupList(2));
			Map<Integer, String> resultMap = Maps.newHashMap();
			for(Group group : resultList) {
				resultMap.put(group.getId(), group.getName());
			}
			String title = "用户列表";
			
			 List<String> nameStr = Lists.newArrayList();
			 nameStr.add("账号");
			 nameStr.add("姓名");
			 nameStr.add("部门/班级");
			 nameStr.add("E-mail");
			 nameStr.add("手机号码");
			 
			List<List<String>> tempList = Lists.newArrayList();
			
			for(User user : userList) {
				List<String> userInfo  = Lists.newArrayList();
				userInfo.add(user.getUsername());
				userInfo.add(user.getNickname());
				userInfo.add(resultMap.get(user.getParentId()));
				userInfo.add(user.getEmail());
				userInfo.add(user.getPhoneNumber());
				tempList.add(userInfo);
			}
			return ExportExcelUtil.exportExcel(title, nameStr, tempList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@SystemControllerLog(description="查看日志")
	@RequestMapping("/operateLog")
	public String operateLog(ModelMap modelMap, ActionValueAssistant actionValueAssistant ) throws ParseException {
		String startT = actionValueAssistant.get(String.class,"beginTime");
		String endT = actionValueAssistant.get(String.class,"endTime");
		String userName = actionValueAssistant.get(String.class,"userName");
		Integer pageNo = actionValueAssistant.get(Integer.class,"page");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		Date date = sdf.parse("2008-08-08 12:10:12");
		if(pageNo==null){
			pageNo=1;
		}
		String hql = "from LogRecord where 1=1 ";
		List<Object> valueList = Lists.newArrayList();
		if(!Strings.isNullOrEmpty(startT)){
			hql+="and creatDate > ? ";
			valueList.add(sdf.parse(startT));
		}
		if(!Strings.isNullOrEmpty(endT)){
			hql+="and creatDate < ? ";
			valueList.add(sdf.parse(endT));
		}
		if(!Strings.isNullOrEmpty(userName)){
			hql+="and user like ? ";
			valueList.add("%"+userName+"%");
		}
		hql+="order by creatDate desc";
		modelMap.put("startT", startT);
		modelMap.put("endT", endT);
		modelMap.put("logPage", logRecordManager.findByQuery(hql,valueList.toArray()).getPageByPageNo(pageNo, 12));
		return BASE_URL + "/operateLog/operateLogManager";
	}
	
	@RequestMapping("/userLogData")
	@ResponseBody
	public Map<String,Object> userLogData(ModelMap modelMap,ActionValueAssistant actionValueAssistant) throws ParseException{
		Map<String,Object> resultMap = Maps.newHashMap();
		String startT = actionValueAssistant.get(String.class,"beginTime");
		String endT = actionValueAssistant.get(String.class,"endTime");
		String userName = actionValueAssistant.get(String.class,"userName");
		Integer pageNo = actionValueAssistant.get(Integer.class,"page");
		Integer pageSize = actionValueAssistant.get(Integer.class, "limit");//layui默认pageSize
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(pageNo==null){
			pageNo=1;
		}
		//拼接普通hql语句
		String hql = "select description,methods,user,userid,date_format(creatDate, '%Y-%m-%d %H:%i') from LogRecord where 1=1 ";
		List<Object> valueList = Lists.newArrayList();
		if(!Strings.isNullOrEmpty(startT)){
			hql+="and creatDate > ? ";
			valueList.add(sdf.parse(startT));
		}
		if(!Strings.isNullOrEmpty(endT)){
			hql+="and creatDate < ? ";
			valueList.add(sdf.parse(endT));
		}
		if(!Strings.isNullOrEmpty(userName)){
			hql+="and user like ? ";
			valueList.add("%"+userName+"%");
		}
		hql+="order by creatDate desc";
		//通过这种方法查询数据findProperty
		IPage<Map<String,Object>> page = logRecordManager.findProperty(new String[]{"description","methods","user","userid","creatDate"},hql,valueList.toArray()).getPageByPageNo(pageNo, pageSize);
		//填写序号
		Integer beginIndex = (pageNo-1)*pageSize;
		for(Map<String,Object> map:page.getData()){
			map.put("index", ++beginIndex);
		}
		resultMap.put("count", page.getTotalCount());
		resultMap.put("data", page.getData());
		resultMap.put("code", 0);
		resultMap.put("msg", "");//当数据出错是输出该句子
		
		return resultMap;
		
	}
}
